import { Injectable } from '@nestjs/common'
import { InjectModel } from '@app/transformers/model.transformer'
import { MongooseModel, MongooseDoc, MongooseID } from '@app/interfaces/mongoose.interface'
import { Itinerary } from './itinerary.model'
import { MapService } from '../map/map.service';

@Injectable()
export class ItineraryService {
  // @InjectModel(Itinerary) private readonly itineraryModel: MongooseModel<Itinerary>

  constructor(private readonly amapMcpService: MapService) {}

  // public generateItinerary(generateDto: any): Promise<Itinerary> {
  //   const itinerary = new this.itineraryModel(generateDto);
  //   return itinerary.save();
  // }

  // public async getItinerary(id: MongooseID): Promise<Itinerary | null> {
  //   return this.itineraryModel.findById(id).exec();
  // }

  async generateTravelPlan(destination: string, days: number = 3) {
    // 1. 地理编码，获取目的地的坐标和城市信息
    const geoResult = await this.amapMcpService.geocode(destination);
    const location = geoResult.location;
    const city = geoResult.city || destination;

    // 2. 获取天气信息
    const weather = await this.amapMcpService.getWeather(city);

    // 3. 搜索周边的景点
    const attractions = await this.amapMcpService.aroundSearch(
      location,
      '风景名胜|公园',
      10000
    );

    // 4. 搜索周边的餐饮
    const restaurants = await this.amapMcpService.aroundSearch(
      location,
      '餐饮|美食',
      5000
    );

    // 5. 生成每日行程安排
    const dailyPlans = await this.generateDailyItinerary(
      attractions.pois || [],
      restaurants.pois || [],
      location,
      days
    );

    return {
      destination,
      city,
      location,
      weather: weather.forecasts || [],
      days: dailyPlans,
      totalAttractions: attractions.pois?.length || 0,
      totalRestaurants: restaurants.pois?.length || 0,
    };
  }

  private async generateDailyItinerary(
    attractions: any[],
    restaurants: any[],
    centerLocation: string,
    days: number
  ) {
    const dailyPlans: any[] = [];
    const attractionsPerDay = Math.min(3, Math.ceil(attractions.length / days));

    for (let day = 1; day <= days; day++) {
      const dayAttractions = attractions.splice(0, attractionsPerDay);
      const dayRestaurants = this.selectNearbyRestaurants(
        restaurants,
        dayAttractions
      );

      // 生成当天的路线规划
      const route = await this.planDailyRoute(
        centerLocation,
        dayAttractions,
        dayRestaurants
      );

      dailyPlans.push({
        day,
        attractions: dayAttractions,
        restaurants: dayRestaurants,
        route,
        description: this.generateDayDescription(day, dayAttractions)
      });
    }

    return dailyPlans;
  }

  private async planDailyRoute(
    startLocation: string,
    attractions: any[],
    restaurants: any[]
  ) {
    if (attractions.length === 0) return null;

    const waypoints: any[] = [];

    // 组合景点和餐厅作为途经点
    for (let i = 0; i < attractions.length; i++) {
      waypoints.push(attractions[i].location);

      // 在每个景点后安排一个附近的餐厅
      const nearbyRestaurant = this.findNearestRestaurant(
        restaurants,
        attractions[i].location
      );
      if (nearbyRestaurant) {
        waypoints.push(nearbyRestaurant.location);
      }
    }

    const destination = startLocation; // 返回起点
    const waypointsStr = waypoints.join('|');

    return await this.amapMcpService.drivingRoute(
      startLocation,
      destination,
      waypointsStr
    );
  }

  private selectNearbyRestaurants(restaurants: any[], attractions: any[]) {
    // 简化的就近餐厅选择逻辑
    return restaurants.slice(0, Math.min(3, restaurants.length));
  }

  private findNearestRestaurant(restaurants: any[], location: string) {
    return restaurants.length > 0 ? restaurants[0] : null;
  }

  private generateDayDescription(day: number, attractions: any[]) {
    const attractionNames = attractions.map(a => a.name).join('、');
    return `第${day}天行程：游览${attractionNames}`;
  }
}
